<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户注册控制器
 * @author Calvin
 *
 * @modify Calvin
 *
 */

class Register extends CI_Controller{

	private $_invite = false;  //邀请码开关
	
	public function __construct(){
		parent::__construct();

		$services = array(
			'register_service',
			'user_verify_service',
			'login_service',
			'user_info_service',
			'invite_service'
		);
		$this->load->service($services);

		$this->load->library("form_validation");
		$this->config->load("form_validation");
		$this->_invite = $this->config->item("invite");
	}
	
	//注册视图
	public function index(){
		$this->load->library('user_agent');
		if($this->agent->is_mobile()){
			redirect("/m/index.html#login/register");
		}

		//生成唯一标识符
		$uniqid = Common::uniqid();
		$this->session->set_userdata('__UNIQID__', $uniqid);

        //获取此ip注册次数,5次以上要验证码注册
		//$show_vcode = $this->register_service->vcode_required();
		$this->template->assign('show_vcode', FALSE);
		$sms_code_len=$this->config->item("sms_verify_code_length","user_common");

		$invite_code 	= trim($this->input->get('code', true));
		$email 			= trim($this->input->get('email', true));

		$this->template->assign('code',  $invite_code);
		$this->template->assign('email', $email);
		$this->template->assign('invite', $this->_invite);
		$data = array(
				'uniqid' => $uniqid,
				'title'  => '注册',
				"sms_code_len"=>	$sms_code_len
		);
		$this->template->view('user/register.tpl', $data);
	}

	//生成验证码
	public function code(){
		$config = array(
				'width'	=>	80,
				'height'=>	34,
				'codeLen'=>	4,
				'fontSize'=>16
		);
		$this->load->library('code', $config);
		$this->session->set_userdata('__REGISTER_VCODE__', $this->code->getCode());
		$this->code->show();
	}
	
	//ajax检查验证码
	public function check_code(){
		$code = $this->input->post('code',true);
		if(!$code || strtoupper($code) != $this->session->userdata('__REGISTER_VCODE__')){
			return Common::ajax_return(1007);
		}
		return Common::ajax_return();
	}
	
	//ajax检查邮箱有无已被注册
	public function check_email()
	{
		$this->form_validation->set_rules('email','', 'required|valid_email');
		if($this->form_validation->run()==FALSE)
		{
			return Common::ajax_return(1003);
		}
		$email = trim($this->input->post('email',true));
		$userData = $this->register_service->check_email_exists($email);
		if($userData){
			if($userData['verify'] == 0){
				if($this->register_service->check_overdue_by_email($email)){
					return Common::ajax_return();
				} else {
					$data = Common::get_email_url($email);
					//self::ret_error(3, '该邮箱已被注册但没有激活', $data);
					return Common::ajax_return(5010,NULL,array("host"=>$data,"email"=>$email),FALSE);
				}
			}
			return Common::ajax_return(5001);
		}
		return Common::ajax_return();
	}

	/**
	 * 邀请码检测
	 * @return array
	 */
	public function check_invitation_code() {
		$code = trim($this->input->post('invitation_code', true));
		$invite_res = $this->invite_service->code($code);
		if ($invite_res['error_code'] !== 0) {
			if ($invite_res['error_code'] == 1404)
				return Common::ajax_return(1051);

			return Common::ajax_return(1053);
		}

		if ($invite_res['status'] == 2)
			return Common::ajax_return(1052);

		return Common::ajax_return(0);
	}

	private function _invite_reg() {
		#邀请注册
		if ($this->_invite) {
			$invite_code = trim($this->input->post('invitation_code', true));
			$invite_res = $this->invite_service->check($invite_code);
var_dump($invite_res);
			if ($invite_res['error_code'] !== 0) {
				if ($invite_res['error_code'] == 1404)
					return Common::ajax_return(1051);

				return Common::ajax_return(1053);
			}

			if ($invite_res['status'] == 2)
				return Common::ajax_return(1052);
		}
	}
	/**
	 * 注册表单处理
	 * @return bool
	 */
	public function register_by_email(){
		$this->_invite_reg();

		//防止跨站恶意注册
		$uniqid = $this->input->post('uniqid',true);
		if(!$uniqid || $uniqid != $this->session->userdata('__UNIQID__')){
			show_404();
		}
		/*$vcode = $this->session->userdata('__REGISTER_VCODE__');
		//是否检查验证码
		if(!empty($vcode) || $this->register_service->vcode_required()){
			$code = $this->input->post('code',true);
			if(!$code || strtoupper($code) != $vcode){
				return Common::ajax_return(1007);
			}
		}*/
		//验证表单
		if ($this->form_validation->run("register_by_email") == FALSE)
		{
			return Common::ajax_return(1003);
		}


		$email = trim($this->input->post('email', true));
		$password = $this->input->post('password',true);
		$n_phone = $this->input->post('n_phone',true);
		$register =$this->register_service->register_by_email($email,$password,$n_phone);
		if($register!==false)
		{
			$send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_REGISTER,"register/active");
			if($send)
			{
				//$this->send_email_success($email);
				return Common::ajax_return(0,NULL,array("redirect"=>"/register/send_email_success/".urlencode($email)),FALSE);
			}
			else
			{
				return Common::ajax_return($this->user_verify_service);
			}
		}
		else
		{
			return Common::ajax_return($this->register_service);
		}

	}

	/**
	 *
	 * 显示错误信息
	 * @param $msg
	 * @param string $title
	 * @param string $type
	 */
	private function show_result($msg,$title="错误提示",$type="error")
	{
		$data['msg'] = $msg;
		$data['title'] = $title;
		$data['type'] = $type;
		$this->template->view('common/tips.tpl', $data);
	}

	/**
	 * 邮件发送成功
	 */
	public function send_email_success($email=""){
		$email = !empty($email)?$email:$this->input->get("email");
		if(empty($email))
		{
			show_404();
		}
		$email = urldecode($email);
		$to_email_url = Common::get_email_url($email);
		$isTryout = 0;
		$tryout = $this->login_service->get_tryout();
		if(!empty($tryout)){
			$isTryout = 1;
		}
		$this->template->assign('isTryout', $isTryout);
		$this->template->assign('email', $email);
		$this->template->assign('to_email_url', $to_email_url);
		$this->template->assign('title', '注册');
		$this->template->view('user/user_active.tpl');
	}

	/**
	 * 邮件发送失败
	 */
	public function send_email_error($email=""){
		$email = !empty($email)?$email:$this->input->get("email");
		if(empty($email))
		{
			show_404();
		}
		$link_me = $this->user_verify_service->get_sender_email();
		$data = array(
			'title' => '注册',
			'model' => 'send_email_error',
			'link_me'=>$link_me[0],
			'email'	=> $email
		);
		$this->template->view('user/tips.tpl',$data);
	}
	//发送注册邮箱
	/*public function verify_reset_send($email=""){
		$email = !empty($email)?$email:$this->input->get("email");
		if(empty($email))
		{
			show_404();
		}
		$email = urldecode($email);
		$send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_REGISTER,"register/active");
		if($send!==false)
		{
			$this->send_email_success($email);
			return true;
		}
		$error = $this->user_verify_service->get_error();
		$this->show_result($error['msg']);
	}*/

	/**
	 * 重新发送注册邮件
	 * @return bool
	 */
	public function resend_register_email()
	{
		$this->form_validation->set_rules('email','', 'required|valid_email');
		if($this->form_validation->run()==FALSE)
		{
			return Common::ajax_return(1003);
		}
		$email = $this->input->post("email",TRUE);
		$check_active = $this->user_verify_service->check_email_not_active($email);
		if(!$check_active)
		{
			return Common::ajax_return($this->user_verify_service);
		}
		$send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_REGISTER,"register/active");
		if($send!==false)
		{
			return Common::ajax_return(0,NULL,array("redirect"=>"/register/send_email_success/".urlencode($email)),FALSE);
		}
		else
		{
			return Common::ajax_return($this->user_verify_service);
		}
	}
	
	/**
	 * 邮箱激活
	 */
	public function active($code=""){
		$check = $this->user_verify_service->check_email_verify_code($code,"",User_verify_service::PROCESS_REGISTER,TRUE,TRUE);
		if($check===false){
			$data = array(
				'title' => '注册',
				'model' => 'user_active'
			);
			$this->template->view('user/tips.tpl',$data);
		}
		else
		{
			//激活账号
			$this->register_service->delete_register_log();
			if(!empty($check['session_id']))
			{
				//销毁试用用户session
				$this->session->global_destroy($check['session_id']);
			}
			//卸载试用用户信息
			$this->login_service->unset_tryout();
			$this->register_service->active_user_by_email($check['receiver']);
			//登录
			$this->login_service->login_by_email($check['receiver']);
			$uid = $this->login_service->get_user_info("id");
			//标记用户为已验证用户
			$this->user_info_service->user_verified($uid);
			//成功跳转
			redirect('files');
		}
	}
	
	/**
	 * 重新发送
	 */
	/*public function reset_send(){
		$email = $this->input->get_post('email',true);
		$email = urldecode($email);
		if(empty($email))
		{
			show_404();
		}
		$can_send = $this->user_verify_service->can_send_email($email,User_verify_service::PROCESS_REGISTER,TRUE);
		if($can_send===false)
		{
			$error = $this->user_verify_service->get_error();
			self::ret_error($error['code'],$error['msg']);
		}
		$send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_REGISTER,"register/active");
		if($send === false)
		{
			$error = $this->user_verify_service->get_error();
			self::ret_error($error['code'],$error['msg']);
		}
		self::ret_error(1,"发送成功");
	}*/

	/**
	 * 发送短信
	 */
	public function send_sms()
	{
		$this->form_validation->set_rules('phone','', 'required|valid_mobile_phone');
		if ($this->form_validation->run() == FALSE)
		{
			return Common::ajax_return(1003);
		}
		else
		{
			$mobile = $this->input->post("phone",TRUE);
			$send = $this->user_verify_service->send_sms($mobile,User_verify_service::PROCESS_REGISTER);
			if($send === FALSE)
			{
				return Common::ajax_return($this->user_verify_service);
			}
			return Common::ajax_return();
		}
	}
	//ajax检查邮箱有无已被注册
	public function check_phone(){
		//$this->load->helper(array('phone'));
		//$this->load->library('form_validation');
		$this->form_validation->set_rules('phone','', 'valid_mobile_phone');
		if ($this->form_validation->run() == FALSE)
		{
			return Common::ajax_return(1003);
		}
		else
		{
			$phone = $this->input->post("phone",TRUE);
			$check = $this->register_service->check_phone_exists($phone);
			$ignore = $this->input->post("ignore",TRUE);
			if($check)
			{
				return Common::ajax_return(5009);
			}
			if(empty($ignore))
			{
				$can_send = $this->user_verify_service->can_send_sms($phone,User_verify_service::PROCESS_REGISTER);
				if($can_send===FALSE)
				{
					$err_code =$this->user_verify_service->get_error("code");
					if($err_code==6003||$err_code==6004)
					{
						$error = $this->user_verify_service->get_error();
						return Common::ajax_return(0,$error['msg'],$error['info']);
					}
					else
					{
						return Common::ajax_return($this->user_verify_service);
					}
				}
			}
			return Common::ajax_return();
		}

	}

	public function check_sms_verify_code()
	{
		//$this->load->library('form_validation');
		$this->form_validation->set_rules('phone','', 'required|valid_mobile_phone');
		$this->form_validation->set_rules('sms_vcode','', 'required');
		//Common::console($this->form_validation->run());
		//var_dump($this->form_validation->run());
		if ($this->form_validation->run() == FALSE)
		{
			return Common::ajax_return(1003);
		}
		$code = $this->input->post("sms_vcode",TRUE);
		$phone = $this->input->post("phone",TRUE);
		$check =$this->user_verify_service->check_sms_code($code,$phone,User_verify_service::PROCESS_REGISTER,FALSE);
		if($check===FALSE)
		{
			return Common::ajax_return($this->user_verify_service);
		}
		return Common::ajax_return();
	}


	public function register_by_phone()
	{
		#邀请注册
		$this->_invite_reg();

		$uniqid = $this->input->post('uniqid',true);
		if(!$uniqid || $uniqid != $this->session->userdata('__UNIQID__')){
			show_404();
		}
		//是否检查验证码
		/*$vcode = $this->session->userdata('__REGISTER_VCODE__');
		if(!empty($vcode) || $this->register_service->vcode_required())
		{
			$code = $this->input->post('code',true);
			if(!$code || strtoupper($code) != $vcode){
				return Common::ajax_return(1007);
			}
		}*/
		if ($this->form_validation->run("register_by_phone") == FALSE)
		{

			return Common::ajax_return(1003);
		}


		//邮箱判断
		$phone = trim($this->input->post('phone', true));
		$password = $this->input->post('password',true);
		$n_email = $this->input->post('n_email',true);

		$sms_vcode = $this->input->post("sms_vcode",TRUE);
		if(!$this->user_verify_service->check_sms_code($sms_vcode,$phone,1,TRUE))
		{
			return Common::ajax_return($this->user_verify_service);
		}

		$register =$this->register_service->register_by_phone($phone,$password,$n_email);
		if($register!==false)
		{
			$this->register_service->delete_register_log();
			//销毁试用用户session
			//$this->login_service->logout();
			//$this->session->global_destroy($check['session_id']);
			//登录
			if(!empty($check['session_id']))
			{
				//销毁试用用户session
				$this->session->global_destroy($check['session_id']);
			}
			//卸载试用用户信息
			$this->login_service->unset_tryout();
			$this->login_service->login_by_uid($this->register_service->get_register_uid());
			return Common::ajax_return(0,NULL,array("redirect"=>"/files"),FALSE);
		}
		else
		{
			return Common::ajax_return($this->register_service);
		}
	}
	/**
	 * 错误处理
	 */
	static function ret_error($code = 1, $error = '', $data = null){
		$data = array(
				'ret'       => $code,
				'error'     => $error,
				'data'      => $data
		);
		echo json_encode($data);
		die();
	}

}